var oper = getQueryString('oper')
var sysId = getQueryString('id')

var baseUrl = '/pages/pre/report/type/'
var querySys = "/comm/insystem/insys_list";
var queryOutSys = "/comm/outsystem/outsys_list";
var queryGroup = "/comm/group/group_list/code/";
var createTcpPage = baseUrl + "tcpEdit";
var createJmsPage = baseUrl + "jmsEdit";
var createMqPage = baseUrl + "MQEdit";
var createTlqPage = baseUrl + "TlqEdit";
var createHttpPage = baseUrl + "httpEdit";
var createHttpsPage = baseUrl + "httpsEdit";
var createWSPage = baseUrl + "wsEdit";
var createCustomPage = baseUrl + "customEdit";
var saveConfig = "/comm/syscommconfig/save";
var updateConfig = "/comm/syscommconfig/updateById";
var detailData = {}
var recvRule,connetionType,httpEntry = [];
$(function () {

  $('#oper').val(oper)
  if (oper === 'edit' || oper === 'view') {
    getDetail(sysId)
  }
  $.common.initFormInfo();

  //渲染通讯协议字典
  renderDictFilter('#comm_Select', 'protocol_type')
  renderDictFilter('#commType', 'comm_type')
  bindEvents();
});


function getDetail(id) {
  $.operate.get(api + '/comm/syscommconfig/check?confId=' + id, function (res) {
    var commType = res.data.commType;
    var temp_systemCode = res.data.systemCode;
    var temp_groupCode = res.data.groupCode;
    recvRule = res.data.recvRule ? res.data.recvRule : ''
    connetionType = res.data.connetionType
    httpEntry = res.data.entry ? res.data.entry : []
    if (commType) {
      if ("OUT" == commType) {
        res.data.sysOutId = temp_systemCode
        if ("" == temp_systemCode && "" == temp_groupCode) {  //新增显示创建
          $("#comm_baseDataDiv").find("#comm_query_btn_div").remove();
          // $("#comm_cfg_div").append(addQeueryBtn());
          $("#comm_query_btn_div").show()
        } else {
          //禁用选项
          $("#comm_Select").attr("disabled", "disabled");
          $("#commType").attr("disabled", "disabled");
          $("#systemCode_select").attr("disabled", "disabled");
          $("#groupCode_select").attr("disabled", "disabled");
          $("#systemCode_select_out").attr("disabled", "disabled");
          $("#comm_query_btn_div").hide()
        }
        $("#comm_baseDataDiv").hide();
        $("#comm_id_div").show();
        initCommSelectData_Out(temp_systemCode);
      }
      if ("IN" == commType) {
        if ("" == temp_systemCode && "" == temp_groupCode) {  //新增显示创建
          $("#comm_cfg_div").find("#comm_query_btn_div").remove();
          // $("#comm_baseDataDiv").append(addQeueryBtn());
          $("#comm_query_btn_div").show()
        } else {
          //禁用选项
          $("#comm_Select").attr("disabled", "disabled");
          $("#commType").attr("disabled", "disabled");
          $("#systemCode_select").attr("disabled", "disabled");
          $("#groupCode_select").attr("disabled", "disabled");
          $("#systemCode_select_out").attr("disabled", "disabled");
          $("#comm_query_btn_div").hide()
        }
        $("#comm_baseDataDiv").show();
        $("#comm_id_div").hide();
        initCommSelectData(temp_systemCode, temp_groupCode);
      }
    } else {
      initCommSelectData();
      initCommSelectData_Out();
    }
    detailData = res.data
    applyDrawing('#comm_cfg_query_form', res.data)
    $.common.initFormInfo();
  }, false)
}

function submitHandler() {
  if ($.validate.form()) {
    // $.common.ajaxCommitForm($('#editForm'), false);
    saveCommCfg()
    return false;
  }
}

//获取接入项目列表
function getInsystem() {
  $.operate.get(api + '/comm/insystem/insys_list', function (res) {
    res.data.forEach(function (item) {
      $('#systemCode_select').append('<option value="' + item.code + '">' + item.name + '</option>')
    })
  }, false)
}

//获取接出项目列表
function getOutsystem() {
  $.operate.get(api + '/comm/outsystem/outsys_list', function (res) {
    res.data.forEach(function (item) {
      $('#systemCode_select_out').append('<option value="' + item.code + '">' + item.name + '</option>')
    })
  }, false)
}

//根据接入项目名称获取服务列表
function getGroup(code) {
  $('#groupCode_select').find('option').remove()
  $('#groupCode_select').append('<option value=""></option>')
  $.operate.get(api + '/comm/group/group_list/code/' + code, function (res) {
    res.data.forEach(function (item) {
      $('#groupCode_select').append('<option value="' + item.code + '">' + item.name + '</option>')
    })
  }, false)
}


function initCommSelectData_Out(systemCode) {
  $.operate.get(queryOutSys, function (data) {
    $("#systemCode_select_out").empty();
    $("#systemCode_select_out").append("<option value=''>--请选择--</option>");
    var sysId;
    data.data.forEach(function (val, index) {
      if (systemCode && systemCode == val.code) {
        $("#systemCode_select_out").append("<option selected='selected' value=" + val.code + ">" + val.name + "</option>");
        sysId = val.sysId;
      } else {
        $("#systemCode_select_out").append("<option value=" + val.code + ">" + val.name + "</option>");
      }
      //$("#systemCode_select_out").append("<option value=" + val.sysId + ">" + val.sysName +"</option>");
      //$("#systemCode_select_out").append("<option value=" + val.sysCode + ">" + val.sysName +"</option>");
      $("#comm_baseDataDiv").append("<input type='hidden' value=" + val.code + " name='sysCode' id='" + val.sysId + "codeTxt'>");
    });
    queryCommConfig();
  }, false);
}

function initCommSelectData(systemCode, groupCode) {
  $.operate.get(querySys, function (data) {
    $("#systemCode_select").empty();
    $("#systemCode_select").append("<option value=''>请选择</option>");
    var sysId;
    data.data.forEach(function (val, index) {
      if (systemCode && systemCode == val.code) {
        $("#systemCode_select").append("<option selected='selected' value=" + val.code + ">" + val.name + "</option>");
        sysId = val.sysId;
      } else {
        $("#systemCode_select").append("<option value=" + val.code + " data-code=" + val.code + ">" + val.name + "</option>");
      }
      $("#comm_baseDataDiv").append("<input type='hidden' value=" + val.code + " name='sysCode' id='" + val.sysId + "codeTxt'>");
    })
    if (groupCode) {
      initCommmGroup(sysId, groupCode, systemCode);
    }
  }, false);
}


function queryCommConfig() {
  var comm = $("#comm_Select").val();   // 选择的协议类型等  如  http  https....
  if ($("#comm_cfg_query_form").valid()) {
    var url = getPageUrl(comm);
    $.ajaxSettings.async = false;
    $("#packet_context_div").empty();
    $("#packet_context_div").load(url);
    if (undefined != url) {
      $("#comm_cfg_form").attr("style", "display:block;");
      applyDrawing('#comm_cfg_form', detailData)
    }
  }
}

function createComm() {
  var comm = $("#comm_Select").val();   // 选择的协议类型等  如  http  https....
  if ($("#comm_cfg_query_form").valid()) {

    var commUrl = '/comm/syscommconfig/check?'
    var queryData = {
      systemCode: $('#commType').val() == "IN" ? $('#systemCode_select').val() : $('#systemCode_select_out').val(),
      groupCode: $('#groupCode_select').val(),
      commType: $('#commType').val() == "IN" ? 0 : 1,
      commProtocol: comm,
    }
    Object.keys(queryData).map(function(key){
      commUrl += key + '=' + queryData[key] +'&';
    })
    commUrl = commUrl.substr(0,commUrl.length-1)
    $.operate.get(api + commUrl, function (res) {
      var url = getPageUrl(comm);
      // $.ajaxSettings.async = false;
      if (res.data) {
        sysId = res.data.confId
        $.modal.confirm('你加载的配置已经存在，确认需要修改吗？', function () {

          recvRule = res.data.recvRule ? res.data.recvRule : ''
          connetionType = res.data.connetionType
          httpEntry = res.data.entry ? res.data.entry : []
          $.ajaxSettings.async = false;
          $("#packet_context_div").empty();
          $("#packet_context_div").load(url);
          if (undefined != url) {
            $("#comm_cfg_form").attr("style", "display:block;");
            applyDrawing('#comm_cfg_form', res.data)
          }
        })
      } else {
        $("#packet_context_div").empty();
        $("#packet_context_div").load(url);
        if (undefined != url) {
          $("#comm_cfg_form").attr("style", "display:block;");
          // applyDrawing('#comm_cfg_form', res.data)
        }
      }


    }, false)


  }
}

function addQeueryBtn() {
  return '<div id="comm_query_btn_div" class="col-sm-2" style="text-align:right;padding-right:20px;">' +
    '<button type="button" id="create_btn" onclick="createComm()" class="btn btn-primary fa fa-search" style="margin-right:4px;">创建</button>' +
    '</div>';
}


/**
 * 绑定事件
 */
function bindEvents() {
  $("#systemCode_select").bind('change', function () {
    $("#packet_context_div").empty();
    $("#groupCode_select").empty();
    var val = $(this).find("option:selected").data('code')
    if (val) {
      $.ajax({
        url: queryGroup + val,
        type: "get",
        contentType: 'application/json;charset=utf-8', // 设置请求头信息
        dataType: "json",
        success: function (data) {
          data.data.forEach(function (val, index) {
            $("#groupCode_select").append("<option value=" + val.code + ">" + val.name + "</option>");
          })
        }
      });
    }

  });

  //
  $("#systemCode_select_out").bind('change', function () {
    $("#packet_context_div").empty();
  });

  $("#groupCode_select").bind('change', function () {
    $("#packet_context_div").empty();
  });

  /**
   * 绑定通讯类型改变值事件
   */
  $("#commType").bind('change', function () {
    $("#packet_context_div").empty();
    var type = $("#commType").val();
    if (!type) {
      $("#comm_query_btn_div").hide()
      $("#comm_baseDataDiv").hide()
      $("#comm_id_div").hide()
    }
    if ("OUT" == type) {
      //判断 如果通信协议是自定义则提示接出无自定义通讯类型
      if ($("#comm_Select").val() == "custom") {
        $.modal.alertError("接出不支持自定义通讯类型，请重新选择！");
        $("#comm_Select").val("");
        // $("#comm_cfg_div").append(addQeueryBtn());
        $("#comm_query_btn_div").hide()
        $("#comm_baseDataDiv").hide();
        // $("#comm_id_div").show();
        // $("#comm_baseDataDiv").find("#comm_query_btn_div").remove();
        // initCommSelectData_Out();
        return;
      }
      // $("#comm_cfg_div").append(addQeueryBtn());
      $("#comm_query_btn_div").show()
      $("#comm_baseDataDiv").hide();
      $("#comm_id_div").show();
      $("#comm_baseDataDiv").find("#comm_query_btn_div").remove();
      initCommSelectData_Out();
    }
    if ("IN" == type) {
      $("#comm_id_div").hide();
      $("#comm_cfg_div").find("#comm_query_btn_div").remove();
      // $("#comm_baseDataDiv").append(addQeueryBtn());
      $("#comm_query_btn_div").show()
      $("#comm_baseDataDiv").show();
      // initCommSelectData("[[${systemCode}]]","[[${groupCode}]]");
      initCommSelectData();
    }
  });


  /**
   * 类型选择绑定事件
   */
  $("#comm_Select").bind('change', function () {
    if ($("#commType").val() == "OUT") {
      if ($(this).val() == "custom") {
        $.modal.alertError("接出不支持自定义通讯类型，请重新选择！");
        $("#commType").val("");
      }
    }
    $("#packet_context_div").empty();
    $("#comm_cfg_form").attr("style", "display:none;")

    var type = $("#commType").val();
    if (!type) {
      $("#comm_query_btn_div").hide()
      $("#comm_baseDataDiv").hide()
      $("#comm_id_div").hide()
    }
    if ("OUT" == type) {
      // $("#comm_cfg_div").append(addQeueryBtn());
      $("#comm_query_btn_div").show()
      $("#comm_baseDataDiv").hide();
      $("#comm_id_div").show();
      $("#comm_baseDataDiv").find("#comm_query_btn_div").remove();
      initCommSelectData_Out();
    }
    if ("IN" == type) {
      $("#comm_id_div").hide();
      $("#comm_cfg_div").find("#comm_query_btn_div").remove();
      // $("#comm_baseDataDiv").append(addQeueryBtn());
      $("#comm_query_btn_div").show()
      $("#comm_baseDataDiv").show();
      // initCommSelectData("[[${systemCode}]]","[[${groupCode}]]");
      initCommSelectData();
    }

  });

}

function initCommmGroup(sysId, groupCode, sysCode) {
  $("#groupCode_select").empty();
  $.ajax({
    url: queryGroup + sysCode,
    type: "get",
    contentType: 'application/json;charset=utf-8', // 设置请求头信息
    dataType: "json",
    success: function (data) {
      data.data.forEach(function (val, index) {
        if (groupCode && groupCode == val.code) {
          $("#groupCode_select").append("<option selected='selected' value=" + val.code + ">" + val.name + "</option>");
        } else {
          $("#groupCode_select").append("<option value=" + val.code + ">" + val.name + "</option>");
        }
      })
      queryCommConfig();
    }
  });
}

//保存通讯
function saveCommCfg() {
  if (!$("#comm_cfg_query_form").valid()) {
    return;
  }
  if ($("#comm_cfg_form").valid()) {
    var data = $("#comm_cfg_form").serializeObject();
    var type = $("#comm_Select").val();
    //通讯类型
    data.type = type;
    if (type == "http") {
      //http类型添加头信息
      var entry = [];
      var keys = $("input[keyType='key']").each(function (index, element) {
        //获取key值
        var kval = $(this).val();
        var vval = $(this).parents('.form-group').siblings('.form-group').find("input").val();
        var item = {};
        item.key = kval;
        item.value = vval;
        entry.push(item);
      });
      data.entry = entry;
    }
    if (type == "https") {
      //http类型添加头信息
      var entry = [];
      var keys = $("input[keyType='key']").each(function (index, element) {
        //获取key值
        var kval = $(this).val();
        var vval = $(this).parents('.form-group').siblings('.form-group').find("input").val();
        var item = {};
        item.key = kval;
        item.value = vval;
        entry.push(item);
      });
      data.entry = entry;
    }
    if (type == "custom") {
      var entry = [];
      var keys = $("input[keyType='key']").each(function (index, element) {
        //获取key值
        var kval = $(this).val();
        var vval = $(this).parents('.form-group').siblings('.form-group').find("input").val();
        var item = {};
        item.key = kval;
        item.value = vval;
        entry.push(item);
      });
      data.entry = entry;
    }
    //处理连接类型
    var connType = data.connetionType;
    //tcp和http在本来的类型上加上长，短连接
    if (type == "tcp") {
      // var realType = data.type
      // data.type = realType + ":" + connType;
      if ("" == data.recvRule) {
        data.recvRule = undefined;
      }
    }
    //项目编码
    // data.systemCode = $("#"+$("#systemCode_select").val()+"codeTxt").val();
    //接入接出处理
    var commType = $("#commType").val();
    if (commType == "OUT") {
      //data.groupCode = $("#comm_cfg_id_txt").val();
      data.groupCode = "";
      data.systemCode = $("#systemCode_select_out").val();
      // data.id = $("#systemCode_select_out").val();
    } else {
      data.groupCode = $("#groupCode_select").val();
      data.systemCode = $("#systemCode_select").val();
      // data.id = data.systemCode + "." + data.groupCode
    }
    data.commType = commType;
    // data.connetionType = null;
    if (sysId) data.confId = Number(sysId)
    var parent = window.parent
    $.ajax({
      url: data.confId ? updateConfig : saveConfig,
      type: data.confId ? "put" : "post",
      contentType: 'application/json;charset=utf-8', // 设置请求头信息
      dataType: "json",
      data: JSON.stringify(data), // 将Json对象序列化成Json字符串，JSON.stringify()原生态方法
      success: function (result) {
        if (result.code == 0) {
          $.modal.close()
          parent.$.modal.msgSuccess('保存成功');
          parent.$.table.refresh();
        } else {
          $.modal.msgError(result.message);
        }
      }
    });
  }

}

function getSuffix() {
  var commType = $("#commType").val();
  if ("IN" == commType) {
    var sysId = $("#systemCode_select").val();
    var systemCode = $("#" + sysId + "codeTxt").val();
    var groupCode = $("#groupCode_select").val();
    return "systemCode=" + sysId + "&groupCode=" + groupCode;
  } else if ("OUT" == commType) {
    var id = $("#systemCode_select_out").val();
    return "systemCode=" + id + "&groupCode=";
  }
  return "";
}

/**
 *
 * @param type
 *            通讯类型
 * @returns {String}页面请求url
 */
function getPageUrl(type) {
  var url;
  var suffix = getSuffix();
  var commType = $("#commType").val();
  if ("tcp" == type) {
    url = createTcpPage + "?" + suffix;
  } else if ("http" == type) {
    if ("" != commType) {
      url = createHttpPage + "?type=" + commType + "&" + suffix;
    }
  } else if ("jms" == type) {
    if ("" != commType) {
      url = createJmsPage + "?type=" + commType + "&" + suffix;
    }
  } else if ("mq" == type) {
    if ("" != commType) {
      url = createMqPage + "?type=" + commType + "&" + suffix;
    }
  } else if ("tlq" == type) {
    if ("" != commType) {
      url = createTlqPage + "?type=" + commType + "&" + suffix;
    }
  } else if ("https" == type) {
    if ("" != commType) {
      url = createHttpsPage + "?type=" + commType + "&" + suffix;
    }
  } else if ("ws" == type) {
    if ("" != commType) {
      url = createWSPage + "?type=" + commType + "&" + suffix;
    }
  } else if ("custom" == type) {
    if ("" != commType) {
      url = createCustomPage + "?type=" + commType + "&" + suffix;
    }
  }
  return url
}

function goback2Comm() {
  $("#mainFrame").load(locat + "/commCfg/goComm")
}